import { defineStore } from 'pinia'

export const useUser = defineStore('user', {
  state: () => ({
    id: '',
    name: localStorage.getItem('username') || '',
    token: localStorage.getItem('usertoken') || '',
    data: {},
    accessToken: localStorage.getItem('accessToken') || '',

  }),
  actions: {
    init(fun) {
      if (this.token) {
        // 查询本人信息
        myPost("/user/user_by_token", { usertoken: this.token }, data => {
          this.id = data.userId
          this.name = data.userName
          localStorage.setItem('username', data.userName) // 重新存储一下username，用户登录的用户名可能是全小写的
          data.userSetting = JSON.parse(data.userSetting || "[]")
          data.userInfo = JSON.parse(data.userInfo || "[]")
          fun && fun(this.data = data)
        })
      } else {
        console.log("用户未登录")
      }
      return this
    },

    // 查询用户数据，接收一个用户名
    getUserdata(name, func) {
      myPost("/user/user_by_name", { "username": name }, data => {
        let value = data || {}
        value.userSetting = JSON.parse(value.userSetting || "[]");
        value.userInfo = JSON.parse(value.userInfo || "[]");
        func(data)
      })
    },
    // 退出登录，跳转页面
    userLogout() {
      localStorage.removeItem('username')
      localStorage.removeItem("usertoken")
      QC.Login.signOut()
      window.location = "/"
    },

  },
})